#!/usr/bin/python3
# -*- encoding=utf-8 -*-

import requests
import json,time
import user
import resource
import urlparse
import monitor
import sys

reload(sys)

sys.setdefaultencoding('utf-8')


if __name__ == '__main__':
    
    userName = "optadmin"
    password = "Gridview@123"
    headers = {'Gridview-Token': 'OzSBLmLbGPXR0kWccMmFLA==',}
    session = requests.session()
    
    user = user.User(headers,session)
    result = user.login(userName,password)
    
    print result
    
    print "resource"
    resourceId = '11876188725'
    resource = resource.Resource(headers,session)
    res = resource.getResourceById(resourceId)
    print res.text
   

    res = res.json()
    endpoint = res['resultData']['paramsMap']['ComputeIP']
    print endpoint

    monitor1 = monitor.Monitor(headers,session)
    res1 = monitor1.getMetricById(resourceId)
    #print res1.text 
 
    res = res1.json()
    data = []
    for i in range(len(res['resultData']['CPU'])):
        print i
        
        dict1 = res['resultData']['CPU'][i]['metric'][0]
        print dict1
        times = dict1['time']
        print times
   
        value = dict1['value']
        print value
   
        resourceName = res['resultData']['CPU'][0]['resourceName']
 
        print resourceName

        metric = 'cpu.' + resourceName + '.' + dict1['name'].replace(" ", "")
        print  metric

        dict2 = {}
    
        dict2["metric"] = str(metric)
        dict2["endpoint"] = str(endpoint) 
        dict2["timestamp"] = int(str(times)[:-3])
        dict2["step"] = 10
        dict2["value"] = int(str(value))
        dict2["tags"] = ""
        dict2["extra"] = "data to collector"
    
        data.append(dict2)

    print  data

    print  json.dumps(data)
    url = 'http://172.16.32.28:2080/api/collector/push'
    req = requests.post(url,data=json.dumps(data))
    print req

    print req.text    
     

 
